﻿using System;
using System.Runtime.Serialization;
using Catel.Articles.Base.Data.Attributes;
using Catel.Data;
using Catel.Runtime.Serialization;

namespace Catel.Articles._01___Data_handling.Models
{
    /// <summary>
    /// BackwardsCompatibleObject Data object class which fully supports serialization, property changed notifications,
    /// backwards compatibility and error checking.
    /// </summary>
    [Example("Backwards compatibility object", "Shows how to migrate your current code to the DataObjectBase",
        SourceFileName = "/Models/BackwardsCompatibleObject.cs")]
    [Serializable]
    public class BackwardsCompatibleObject : SavableDataObjectBase<BackwardsCompatibleObject>
    {
        #region Variables
        #endregion

        #region Constructor & destructor
        /// <summary>
        /// Initializes a new object from scratch.
        /// </summary>
        public BackwardsCompatibleObject() { }

        /// <summary>
        /// Initializes a new object based on <see cref="SerializationInfo"/>.
        /// </summary>
        /// <param name="info"><see cref="SerializationInfo"/> that contains the information.</param>
        /// <param name="context"><see cref="StreamingContext"/>.</param>
        protected BackwardsCompatibleObject(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        public string Name
        {
            get { return GetValue<string>(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

        /// <summary>
        /// Register the Name property so it is known in the class.
        /// </summary>
        public static readonly PropertyData NameProperty = RegisterProperty("Name", typeof(string), "Unknown");
        #endregion

        #region Methods
        /// <summary>
        /// Retrieves the actual data from the serialization info.
        /// </summary>
        /// <param name="info"><see cref="SerializationInfo"/>.</param>
        /// <remarks>
        /// This method is called from the OnDeserialized method, thus all child objects
        /// are serialized and available at the time this method is called.
        /// Only use this method to support older serialization techniques. When using this class
        /// for new objects, all serialization is handled automatically.
        /// </remarks>
        protected override void GetDataFromSerializationInfo(SerializationInfo info)
        {
            // Check if deserialization succeeded
            if (DeserializationSucceeded) return;
            
            // Handle deserialization by ourselves
            Name = SerializationHelper.GetString(info, "_name", NameProperty.GetDefaultValue<string>());
        }
        #endregion
    }
}
